<template>
  <div class="f-recipe-main">
    <div class="add_btn_top">
      <!-- 合炉,转炉,分炉,分配 -->
      <!-- submitType: 合炉  -->
      <el-button type="primary" size="mini" @click="submitMerge('合炉')"
        >合炉
      </el-button>

      <!-- submitType: 结束  -->
      <el-button type="primary" size="mini" @click="submitMerge('结束')"
        >发布作业看板
      </el-button>
      <div style="margin: 0 10px" :style="{ color: switchTextColor }">
        {{ switchText }}
      </div>
      <el-switch class="screenSwitch" active-color="#2680D2" v-model="screen">
      </el-switch>
      <!-- <el-button type="primary" size="mini">撤销 </el-button> -->
      <!-- <el-button type="primary" size="mini" @click="handleRelease"
        >发布作业看板</el-button
      > -->
    </div>
    <el-container>
      <el-main
        style="padding: 0; background: #fff"
        class=""
        v-permission="[4, 'list']"
      >
        <div style="width:100%;" class="flex-x flex-center">
          <el-tabs v-model="activeName" @tab-click="handleClick" stretch>
            <el-tab-pane
              v-for="item in manufactureSiteList"
              :key="item.name"
              :label="item.name"
              :name="item.name"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          border
          :row-class-name="tableRowClassName"
          size="small"
          @selection-change="handleSelectionChange"
          :data="furnaceRecipeData"
          height="100px"
          v-adaptive
          style="width: 100%"
        >
          <!-- :row-class-name="tableRowClassName" -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table
                border
                size="mini"
                :data="scope.row.childrenList"
                style="width: 65vw; margin-bottom: 14px; z-index: 10"
                v-if="scope.row.childrenList && scope.row.childrenList.length"
              >
                <el-table-column
                  :show-overflow-tooltip="true"
                  width="150px"
                  prop="token"
                  label="任务号"
                  align="center"
                >
                  <template slot-scope="isscope">
                    <span>{{ isscope.row.token }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="scope.row.state !== '合炉'"
                  :show-overflow-tooltip="true"
                  width="150px"
                  prop="deviceName"
                  label="设备名称"
                  align="center"
                >
                  <template slot-scope="isscope">
                    <el-tooltip
                      v-if="isscope.row.deviceInfo.deviceName"
                      class="item"
                      effect="dark"
                      :content="isscope.row.deviceInfo.deviceToken"
                      placement="top"
                    >
                      <span style="color: #409eff; cursor: pointer">
                        {{ isscope.row.deviceInfo.deviceName }}
                      </span>
                    </el-tooltip>
                  </template>
                </el-table-column>

                <template v-for="(item, index) in getChildColumnList">
                  <el-table-column
                    v-if="item.type === 'formula'"
                    :key="index"
                    :show-overflow-tooltip="true"
                    :width="item.width"
                    :prop="item.prop"
                    :label="item.label"
                    align="center"
                    :type="item.type"
                  >
                    <template slot-scope="props">
                      <el-popover
                        placement="bottom"
                        width="800"
                        trigger="click"
                      >
                        <div style="width: 100%">
                          <el-table
                            v-if="
                              props.row.formulaParameter &&
                                props.row.formulaParameter.length
                            "
                            max-height="500px"
                            min-height="100%"
                            border
                            size="mini"
                            :data="props.row.formulaParameter"
                            style="width: 100%"
                          >
                            <el-table-column
                              v-for="(item, index) in props.row
                                .formulaParameter[0].keys"
                              :label="item"
                              :key="index"
                              align="center"
                            >
                              <template slot-scope="scope">
                                {{ scope.row.values[index] }}
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                        <el-button slot="reference" type="text"
                          >查看工艺</el-button
                        >
                      </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-else
                    :show-overflow-tooltip="true"
                    :key="index"
                    :width="item.width"
                    :prop="item.prop"
                    :label="item.label"
                    align="center"
                  >
                    <template slot-scope="isscope">
                      <span>{{ isscope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
                <el-table-column label="操作" align="center" fixed="right">
                  <template slot-scope="isscope">
                    <el-button
                      size="mini"
                      @click="handleDistribution(isscope.row)"
                      :disabled="isscope.row.state === '合炉'"
                      >选择
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- <el-table
                border
                size="mini"
                :data="scope.row.formulaParameter[0].keys"
                style="width: 65vw; margin-bottom: 14px; z-index: 10"
                v-if="
                  scope.row.formulaParameter &&
                    scope.row.formulaParameter.length
                "
              >
                <el-table-column label="内容\名称" align="center">
                  <template slot-scope="scope">
                    {{ scope.row }}
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in scope.row.formulaParameter"
                  :key="index"
                  :label="'阶段' + (index + 1)"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ item.values[scope.$index] }}
                  </template>
                </el-table-column>
              </el-table> -->
            </template>
          </el-table-column>
          <el-table-column type="selection" width="45" align="center">
          </el-table-column>
          <el-table-column
            width="55"
            type="index"
            label="序号"
            align="center"
          ></el-table-column>
          <template v-for="(item, index) in getColumnList">
            <el-table-column
              v-if="item.type === 'formula'"
              :key="index"
              :show-overflow-tooltip="true"
              :width="item.width"
              :prop="item.prop"
              :label="item.label"
              align="center"
              :type="item.type"
            >
              <template slot-scope="props">
                <el-popover placement="bottom" width="800" trigger="click">
                  <div style="width: 100%">
                    <el-table
                      v-if="
                        props.row.formulaParameter &&
                          props.row.formulaParameter.length
                      "
                      max-height="500px"
                      min-height="100%"
                      border
                      size="mini"
                      :data="props.row.formulaParameter"
                      style="width: 100%"
                    >
                      <el-table-column
                        v-for="(item, index) in props.row.formulaParameter[0]
                          .keys"
                        :label="item"
                        :key="index"
                        align="center"
                      >
                        <template slot-scope="scope">
                          {{ scope.row.values[index] }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <el-button slot="reference" type="text">查看工艺</el-button>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="item.showoverflowtooltip"
              :key="index"
              v-if="isTabShow(item.label) && item.type !== 'formula'"
              :min-width="item.width"
              :prop="item.prop"
              :label="item.label"
              align="center"
              sortable
            >
              <template slot-scope="scope">
                <span
                  v-if="item.prop === 'productionTaskNumber'"
                  @click="checkMaterial(scope.row)"
                  style="color: #409eff; cursor: pointer"
                  >{{ scope.row.productionTaskNumber }}</span
                >
                <!-- <el-tooltip
                  v-if="
                    item.prop === 'deviceTypeName' &&
                    scope.row.deviceAssignment.deviceTypeName
                  "
                  class="item"
                  effect="dark"
                  :content="scope.row.deviceAssignment.deviceTypeName"
                  placement="top"
                >
                  <span style="color: #409eff; cursor: pointer">
                    {{ scope.row.deviceAssignment.deviceTypeName }}
                  </span>
                </el-tooltip> -->
                <div v-if="item.prop === 'deviceName'">
                  <el-tooltip
                    v-if="scope.row.deviceInfo.deviceName"
                    class="item"
                    effect="dark"
                    :content="scope.row.deviceInfo.deviceToken"
                    placement="top"
                  >
                    <span style="color: #409eff; cursor: pointer">
                      {{ scope.row.deviceInfo.deviceName }}
                    </span>
                  </el-tooltip>
                </div>
                <!-- 
                  @click="checkDetails(scope.row.id)"
                  
                 -->
                <span
                  v-if="item.prop === 'token'"
                  style="color: #409eff; cursor: pointer"
                  >{{ scope.row.token }}</span
                >
                <span
                  v-if="
                    item.prop !== 'productionTaskNumber' &&
                      item.prop !== 'token' &&
                      item.prop !== 'deviceName'
                  "
                  >{{ scope.row[item.prop] }}</span
                >
              </template>
            </el-table-column>
          </template>
          <el-table-column
            prop="createdDate"
            label="创建时间"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              {{ scope.row.createdDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="updatedDate"
            label="更新时间"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.updatedDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            align="center"
            width="150px"
            fixed="right"
          >
            <!-- eslint-disable-next-line -->
            <template slot="header" slot-scope="scope">
              <div class="flex-x flex-space" style="padding: 0 20px">
                <div>操作</div>
                <el-popover width="100" trigger="click">
                  <div class="column_search_box">
                    <div class="column_title">自定义表头字段</div>
                    <el-checkbox-group v-model="colCheckList">
                      <div class="flex-y column_search">
                        <el-checkbox
                          :label="item.label"
                          v-for="item in getColumnCheckList"
                          :key="item.label"
                        >
                          {{ item.label }}</el-checkbox
                        >
                      </div>
                    </el-checkbox-group>
                  </div>
                  <span slot="reference" class="el-icon-s-grid"></span>
                </el-popover>
              </div>
            </template>
            <template slot-scope="scope">
              <!-- @click="handleConverterShow(scope.row)" -->
              <el-button
                :disabled="scope.row.state === '分炉'"
                type="primary"
                size="mini"
                @click="handleDistribution(scope.row)"
                >选择
              </el-button>
              <el-dropdown
                @command="command => handleCommand(command, scope.row)"
              >
                <el-button size="mini" style="margin-left: 6px">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    :disabled="types.includes(scope.row.state)"
                    command="split"
                    >分炉</el-dropdown-item
                  >
                  <!-- <el-dropdown-item
                    :disabled="types.includes(scope.row.state)"
                    command="converter"
                    >转炉</el-dropdown-item
                  > -->
                  <!-- :disabled="['初始'].includes(scope.row.state)" -->
                  <el-dropdown-item command="revoke">撤销</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="del">
                    <span style="color: #f56c6c"> 删除 </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <!-- <el-button
                type="primary"
                size="mini"
                @click="handSplit(scope.row)"
                >分炉
              </el-button>
              <el-button
                @click="handleConverterShow(scope.row)"
                type="primary"
                size="mini"
                v-permission="[23, 'button']"
                >转炉
              </el-button>
              <el-button
                @click="handleRevoke(scope.row)"
                type="primary"
                size="mini"
                v-permission="[23, 'button']"
                >撤销
              </el-button>
              <el-button
                @click="handleDel(scope.row.token)"
                type="danger"
                size="mini"
                >删除
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          @pagination="pagination"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          :pageSizes.sync="pageSizes"
        />
      </el-main>
      <el-aside
        style="background: #fff; padding: 10px; margin-left: 10px"
        width="18%"
        v-show="screen"
      >
        <Search :dataAll="dataAll" @setFilterList="setFilterList"></Search
      ></el-aside>
    </el-container>

    <ConverterDialog
      @closeDialog="closeDialog"
      :token="materialToken"
      :showDialog.sync="converterShow"
      :formulaParameter="formulaParameterList"
    ></ConverterDialog>
    <DetailsDialog
      :token="byId"
      :showDialog.sync="showDetailsDialog"
    ></DetailsDialog>
    <MaterialDialog
      :token="materialToken"
      :showDialog.sync="materialShowDialog"
    ></MaterialDialog>
    <SplitEditDialog
      ref="splitEditDialogRef"
      :showSplit.sync="showSplit"
      :assignData="assignData"
      @closeAssignDialog="closeAssignDialog"
      :deviceOption="deviceOption"
    ></SplitEditDialog>
    <!-- 合炉 -->
    <CombinedFurnacedialog
      :showDialog.sync="showDialogCombined"
      :list="assignData"
    ></CombinedFurnacedialog>
    <DistributionDialog
      ref="distributionDialogRef"
      :form="distributionForm"
      @closeDialog="closeAssignDialog"
      :showDialog.sync="showDistributionDialog"
    ></DistributionDialog>
    <EditDialog
      @submitFormJieDuan="submitFormJieDuan"
      ref="editDialogRef"
      :formulaParameter2="formulaParameter2"
      :showDialog.sync="showEditDialog"
    ></EditDialog>
  </div>
</template>

<script>
const COLUMN_LIST = [
  {
    label: "工艺信息",
    prop: "",
    type: "formula",
    width: "150px",
    hideCheck: true // 不进行筛选
  },
  {
    label: "任务号",
    prop: "token",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "状态",
    prop: "state",
    showoverflowtooltip: true,
    width: "150px"
  },
  {
    label: "设备名称",
    prop: "deviceName",
    width: "150px",
    showoverflowtooltip: false
  },
  {
    label: "来件单位",
    prop: "unit",
    hideCheck: true,
    showoverflowtooltip: true,
    width: "150px"
  },
  {
    label: "批次号",
    prop: "batchNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "零件号",
    prop: "partNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "零件名称",
    prop: "partName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "委托工序号",
    prop: "entrustProcessNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "委托工序名称",
    prop: "entrustProcessName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序/工步号",
    prop: "processNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序/工步名称",
    prop: "processName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序版次",
    prop: "version",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工艺版次",
    prop: "version",
    width: "150px",
    showoverflowtooltip: true
  },

  {
    label: "材料牌号",
    prop: "materialMark",
    width: "150px",
    showoverflowtooltip: true
  },

  {
    label: "来件数量",
    prop: "partTotalCount",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "型别",
    prop: "model",
    width: "150px",
    showoverflowtooltip: true
  }
];
const COLUMN_CHILD_LIST = [
  {
    label: "工艺信息",
    prop: "",
    type: "formula",
    width: "150px",
    hideCheck: true // 不进行筛选
  },
  // {
  //   label: "任务号",
  //   prop: "token",
  //   width: "150px",
  //   showoverflowtooltip: true
  // },
  // {
  //   label: "状态",
  //   prop: "state",
  //   showoverflowtooltip: true,
  //   width: "150px"
  // },
  // {
  //   label: "设备名称",
  //   prop: "deviceName",
  //   width: "150px",
  //   showoverflowtooltip: false
  // },
  {
    label: "来件单位",
    prop: "unit",
    hideCheck: true,
    showoverflowtooltip: true,
    width: "150px"
  },
  {
    label: "批次号",
    prop: "batchNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "零件号",
    prop: "partNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "零件名称",
    prop: "partName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "委托工序号",
    prop: "entrustProcessNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序/工步号",
    prop: "processNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序/工步名称",
    prop: "processName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序版次",
    prop: "version",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工艺版次",
    prop: "version",
    width: "150px",
    showoverflowtooltip: true
  },

  {
    label: "材料牌号",
    prop: "materialMark",
    width: "150px",
    showoverflowtooltip: true
  },

  {
    label: "来件数量",
    prop: "partTotalCount",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "型别",
    prop: "model",
    width: "150px",
    showoverflowtooltip: true
  }
];
import { mapGetters } from "vuex";
import Pagination from "@/views/common/page";
import { KEY_ATT } from "@/utils/local";
import ConverterDialog from "./ConverterDialog.vue";
import DetailsDialog from "./DetailsDialog.vue";
import {
  submitMerge,
  formulaList,
  delFormula,
  revoke,
  putFormula
} from "@/api/combinedFurnace";
import MaterialDialog from "../../receive-task/DetailsDialog.vue";
import SplitEditDialog from "./spliceDialog.vue";
import CombinedFurnacedialog from "./CombinedFurnacedialog.vue";
import DistributionDialog from "./DistributionDialog.vue";
import Search from "./searchFilter.vue";
import _ from "lodash";
import EditDialog from "./EditDialog.vue";
import { currentDate } from "@/utils/currentDate";
import { getTemplate } from "@/api/technology";
export default {
  components: {
    Search,
    DistributionDialog,
    DetailsDialog,
    SplitEditDialog,
    Pagination,
    ConverterDialog,
    MaterialDialog,
    CombinedFurnacedialog,
    EditDialog
  },
  computed: {
    ...mapGetters(["manufactureSiteList"]),
    getColumnList() {
      return COLUMN_LIST;
    },
    getChildColumnList() {
      return COLUMN_CHILD_LIST;
    },
    isTabShow() {
      return function(name) {
        return this.colCheckList.includes(name);
      };
    },
    getColumnCheckList() {
      return COLUMN_LIST.filter(item => !item.hideCheck);
    },
    isCasting() {
      const { name } = this.$store.getters.tenant;
      return name == TENANT_TITLE[2];
    }
  },
  data() {
    return {
      activeName: "",
      activeToken: "",
      showEditDialog: false,
      dataAll: [],
      types: ["合炉", "分炉", "转炉"],
      screen: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      distributionForm: {},
      showDistributionDialog: false,
      showDialogCombined: false,
      showSplit: false,
      loading: false,
      showDetailsDialog: false,
      token: "",
      byId: "",
      colCheckList: COLUMN_LIST.map(item => item.label),
      formulaParameterList: [],
      pageNum: 1,
      pageSize: 20,
      pageSizes: [20, 50, 100, 300],
      total: 7,
      otherLabels: KEY_ATT,
      furnaceRecipeData: [],
      assignData: [],
      deviceOption: [],
      from: {},
      converterShow: false,
      materialToken: "",
      materialShowDialog: false,
      searchParams: {},
      rowColorData: {},
      rowColorIndex: 0,
      formulaParameter2: [],
      templateList: [],
      editRow: {}
    };
  },
  mounted() {
    this.activeName = this.$route.query.activeName
      ? this.$route.query.activeName
      : this.manufactureSiteList[0].name;
    this.activeToken = this.manufactureSiteList.find(
      item => item.name == this.activeName
    ).token;
    this.getfurnaceRecipeData();
    formulaList({
      pageNum: 1,
      pageSize: 0,
      pubState: "未发布",
      parentTaskNumber: "ROOT"
    }).then(res => {
      const r = res.data;
      this.dataAll = r.results;
    });
  },
  methods: {
    handleClick(e) {
      this.activeToken = this.manufactureSiteList[e.index].token;
      this.getfurnaceRecipeData();
    },
    submitFormJieDuan(formulaParameter) {
      putFormula(
        {
          ...this.editRow,
          formulaParameter: formulaParameter
        },
        this.editRow.token
      ).then(res => {
        this.$msg({
          type: "success",
          message: "操作成功"
        });
        this.showEditDialog = false;
        this.getfurnaceRecipeData();
      });
    },
    getTemplateList() {
      return new Promise((resolve, reject) => {
        var params = {
          page: 1,
          pageSize: 0
        };
        getTemplate(params).then(res => {
          const { results } = res.data;
          this.templateList = results;
          resolve(results);
        });
      });
    },
    // 编辑阶段
    async handEdit(row) {
      this.editRow = _.cloneDeep(row);
      const { formulaParameter } = row;
      if (!formulaParameter.length) {
        this.$msg("当前不存在阶段信息");
        return;
      }
      //    this. formulaParameterArr2 =
      // this.templateList.find((item) => item.id == templateId)
      //   ?.formulaParameter || [];
      const templateList = await this.getTemplateList();
      let tab = [];
      let val = [];
      // 获取模板下的原始配方参数
      const formulaParameterArr =
        templateList.find(item => item.id == row.templateId)
          ?.formulaParameter || [];
      formulaParameter.forEach(item => {
        let obj = {};
        item.keys.forEach((key, i) => {
          obj[key] = item.values[i];
        });
        val = item.keys.map(m => ({ key: m, value: m, ...item }));
        tab.push(obj);
      });
      val.forEach(item => {
        formulaParameterArr.forEach(ele => {
          if (item.key == ele.key) {
            // 多个参数的时候后边在拓展
            this.$set(item, "additional", ele.additional);
            this.$set(item, "type", ele.type);
          }
        });
      });
      this.showEditDialog = true;
      this.$nextTick(() => {
        this.$refs.editDialogRef.tableData = tab;
        this.$refs.editDialogRef.formulaParameter = val;
      });

      // this.formulaParameter2 = row.formulaParameter;
    },
    handleCommand(command, row) {
      switch (command) {
        // handSplit handleConverterShow handleRevoke handleDel
        case "split":
          this.handSplit(row);
          break;
        case "edit":
          this.handEdit(row);
          break;
        case "converter":
          this.handleConverterShow(row);
          break;
        case "revoke":
          this.handleRevoke(row);
          break;
        case "del":
          this.handleDel(row);
          break;

        default:
          break;
      }
    },
    setFilterList(data) {
      if (data) {
        this.switchTextColor = "#2680D2";
        this.switchText = "显示筛选 ( 已筛选 )";
      } else {
        this.switchTextColor = "#666666";
        this.switchText = "显示筛选";
      }
      this.pageNum = 1;
      this.searchParams = data;
      this.getfurnaceRecipeData(data);
    },
    handleRevoke(row) {
      revoke(row.token).then(res => {
        this.$msg({
          type: "success",
          message: "撤销成功"
        });
        this.getfurnaceRecipeData();
      });
    },
    handleDistribution(row) {
      if (row.state === "分炉") {
        this.distributionForm = row;
      } else {
        this.distributionForm = _.cloneDeep(row);
      }
      this.showDistributionDialog = true;
    },
    handleDel(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delFormula(row.token).then(res => {
          this.$msg({
            type: "success",
            message: "删除成功!"
          });
          this.getfurnaceRecipeData();
        });
      });
    },
    handSplit(row) {
      this.showSplit = true;
      this.$nextTick(() => {
        row.partTotalNumber = Number(row.partTotalNumber);
        this.$refs.splitEditDialogRef.form = _.cloneDeep(row);
      });
      // getFormulaInt({ idList: this.assignData.map((item) => item.id) }).then(
      //   (res) => {
      //     const r = res.data;
      //     this.from = _.cloneDeep(this.assignData[0]);

      //     // this.$refs.splitEditDialogRef.toolingNumber = Number(
      //     //   this.assignData[0].toolingNumber
      //     // );
      //     r.forEach((item) => {
      //       item.deviceList = item.deviceList
      //         ? item.deviceList.map((m) => {
      //             return {
      //               ...m,
      //               deviceTypeName: m.deviceName,
      //               deviceTypeToken: m.deviceToken,
      //             };
      //           })
      //         : [];
      //     });
      //     this.deviceOption = r;

      //   }
      // );
    },
    closeDialog(isRefresh) {
      if (isRefresh) {
        this.getfurnaceRecipeData();
      }
    },
    submitMerge(submitType) {
      const text = submitType == "合炉" ? "合炉" : "发送";

      if (this.assignData.length) {
        if (submitType === "合炉" && this.assignData.length <= 1) {
          this.$msg("请选择两条以上任务合炉");
          return;
        }
        // 只有派工的可以发布
        // const isDispatch = this.assignData.every(
        //   (item) => item.state !== "初始"
        // );
        // if (text == "发送" && !isDispatch) {
        //   this.$msg("状态为初始的任务不可发布!");
        //   return;
        // }
        let flag = false;
        this.assignData.forEach(e => {
          if (!e.deviceInfo.deviceToken && e.state !== "分炉") {
            flag = true;
          }
          if (e.state === "分炉") {
            e.childrenList.forEach(e => {
              if (!e.deviceInfo.deviceToken) {
                flag = true;
              }
            });
          }
        });
        if (text == "发送" && flag) {
          this.$msg("任务或子任务未指派设备!");
          return;
        }
        // 只有初始的可以合炉
        const isInitial = this.assignData.every(item => item.state === "初始");
        if (text == "合炉" && !isInitial) {
          this.$msg("只有初始的任务可以合炉!");
          return;
        }
        const isDevice = this.assignData.every(
          item =>
            this.assignData[0].deviceInfo.deviceToken ===
            item.deviceInfo.deviceToken
        );
        if (text == "合炉" && !isDevice) {
          this.$msg("不同设备的任务不可以合炉!");
          return;
        }
        const isCode = this.assignData.every(
          item => this.assignData[0].categoryCode === item.categoryCode
        );
        if (text == "合炉" && !isCode) {
          this.$msg("不同合炉推荐码不可以合炉!");
          return;
        }
        // this.showDialogCombined = true;
        // return;
        this.$confirm(
          `当前选中 ${this.assignData.length} 个任务,是否确认${text}?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            let list = this.assignData.map(item => item.id);
            let saveList = [];
            for (let item of this.assignData) {
              for (let e of item.childrenList) {
                saveList.push(e.id);
              }
            }
            let taskIdList = [...list, ...saveList];
            submitMerge({
              taskIdList,
              submitType
              // ruleId: "",
              // token: "",
            }).then(res => {
              if (submitType == "结束") {
                this.handleRelease();
              }
              this.getfurnaceRecipeData();
              this.$msg({
                type: "success",
                message: "操作成功"
              });
            });
          })
          .catch(err => {});
      } else {
        this.$msg("请选择任务");
      }
    },
    checkMaterial(row) {
      this.materialToken = row.productionTaskNumber;
      // this.materialToken = "7aa23329-4e32-44a7-9f7d-3f934f35a943";
      this.materialShowDialog = true;
    },
    // 查看详情
    checkDetails(byId) {
      this.byId = byId;
      this.showDetailsDialog = true;
    },
    handleConverterShow(row) {
      this.materialToken = row.token;
      this.formulaParameterList = JSON.parse(
        JSON.stringify(row.formulaParameter)
      );
      this.converterShow = true;
    },
    handleRelease() {
      // this.$router.push({
      //   name: "jobTask"
      // });
      this.$router.push({
        path: "/productionTask/jobTask/list",
        query: {
          activeName: this.activeName
        }
      });
    },
    // 多选
    handleSelectionChange(val) {
      this.assignData = val;
    },
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.getfurnaceRecipeData();
    },
    //table颜色
    // tableRowClassName({ row }) {
    //   return `row_color_${row.categoryCode}`;
    // },
    //获取合炉任务列表
    getfurnaceRecipeData() {
      var that = this;
      that.loading = true;
      var params = {
        pubState: "未发布",
        manufactureSite: this.activeName,
        // state: "结束",
        page: this.pageNum,
        pageSize: this.pageSize,
        includeChildren: true,
        ...this.searchParams,
        stateList:
          this.searchParams && this.searchParams.stateList
            ? this.searchParams.stateList
            : ["初始", "合炉", "分炉"],
        // startDate: data && data.startDate ? data.startDate : currentDate(),
        parentTaskNumber: "ROOT"
      };
      that.furnaceRecipeData = [];
      formulaList(params).then(res => {
        const r = res.data;
        that.total = r.numResults;

        r.results = r.results.map(item => {
          this.initRowColor(item.categoryCode);
          return {
            ...item,
            distribution: false,
            deviceValue: ""
          };
        });

        that.furnaceRecipeData = r.results;
        that.loading = false;
        this.assignData = [];
        this.$nextTick(() => {
          if (this.$refs.multipleTable) {
            this.$refs.multipleTable.clearSelection();
          }
        });
      });
    },

    //table颜色
    tableRowClassName({ row }) {
      if (row.state === "初始") {
        return this.rowColorData[row.categoryCode];
      } else {
        return "";
      }
    },
    // 四种颜色随机,相同的code一样颜色,code超过4从1继续随机
    initRowColor(code) {
      if (!this.rowColorData[code]) {
        if (this.rowColorIndex < 4) {
          this.rowColorIndex++;
          this.rowColorData[code] = `row_color_${this.rowColorIndex}`;
        } else {
          this.rowColorIndex = 1;
          this.rowColorData[code] = `row_color_${this.rowColorIndex}`;
        }
      }
    },
    closeAssignDialog(isRefresh) {
      console.log(typeof isRefresh, isRefresh);
      if (isRefresh && typeof isRefresh == "object") {
        this.distributionForm.deviceInfo = { ...isRefresh };
      }
      if (isRefresh && typeof isRefresh == "boolean") {
        this.getfurnaceRecipeData();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
// @import "~@/styles/mixin.scss";
//table行设置颜色
// /deep/ .el-table .row_color_0 {
//   background: #0cccbc;
// }
// .f-recipe-main /deep/ .el-table {
//   .el-table__fixed-right {
//     background-color: #fff !important;
//     height: 100% !important;
//   }
// }
.f-recipe-main {
  /deep/ .el-table {
    .el-table__body tr.hover-row.current-row > td,
    .el-table__body tr.hover-row.el-table__row--striped.current-row > td,
    .el-table__body tr.hover-row.el-table__row--striped > td,
    .el-table__body tr.hover-row > td {
      background-color: transparent;
    }
    tr:hover > td {
      background-color: transparent !important;
    }
    .row_color_1 {
      background: rgba(121, 233, 110, 0.7);
    }
    .row_color_2 {
      background: rgba(225, 129, 245, 0.7);
    }
    .row_color_3 {
      background: rgba(233, 178, 58, 0.7);
    }
    .row_color_4 {
      background: rgba(83, 178, 233, 0.7);
    }
    .row_color_5 {
      background: rgba(226, 240, 105, 0.7);
    }
  }
}
</style>
